package org.example.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.enums.LogTypeEnum;
import org.example.model.LogRecord;
import org.example.service.LogService;
import org.example.util.CommonUtil;
import org.example.util.JsonUtil;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 谢超
 * @date: 2024/12/2 19:43
 */

@Service
@Slf4j
public class LogServiceImpl implements LogService {

    private static String TOPIC_NAME = "ods_link_visit_topic";

    @Resource
    private KafkaTemplate kafkaTemplate;

    @Override
    public void recordShortLinkLogTest(String msg) {
        log.info("记录日志:{}", msg);
    }

    @Override
    public void recordShortLinkLog(HttpServletRequest request, String shortLinkCode, Long accountNo) {

        // ip 浏览器信息
        String ip = CommonUtil.getIpAddr(request);

        // 请求头信息
        Map<String, String> headerMap = CommonUtil.getAllRequestHeader(request);

        HashMap<String, String> availableMap = new HashMap<>();
        availableMap.put("user-agent", headerMap.get("user-agent"));
        availableMap.put("referer", headerMap.get("referer"));
        availableMap.put("accountNo", accountNo.toString());

        LogRecord record = LogRecord.builder().event(LogTypeEnum.SHORT_LINK_TYPE.name())
                .data(availableMap)
                .ip(ip)
                .ts(CommonUtil.getCurrentTimestamp())
                .bizId(shortLinkCode)
                .build();

        String jsonLog = JsonUtil.obj2Json(record);
        // 打印控制台
        log.info(jsonLog);

        // 发送kafka
        kafkaTemplate.send(TOPIC_NAME, jsonLog);
    }
}
